package com.joe.demo.nio.file;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-28
 */
@Slf4j
public class TestFilesWalkFileTree {

    public static void main(String[] args) throws IOException {
        Files.walkFileTree(Paths.get("G:\\note\\tst"), new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                log.info("进入目录之前：{}", dir);
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                log.info("当前文件: {}", file);
                Files.delete(file);
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                log.info("退出目录之后: {}", dir);
                Files.delete(dir);
                return super.postVisitDirectory(dir, exc);
            }
        });
    }

    public static void m2(String[] args) throws IOException {
        final AtomicInteger javaCount = new AtomicInteger();
        Files.walkFileTree(Paths.get("G:\\note\\netty-demo\\src\\main\\java"), new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toString().endsWith(".java")) {
                    javaCount.incrementAndGet();
                    log.info("Java 文件: {}", file);
                }
                return super.visitFile(file, attrs);
            }
        });
        log.info("java 文件个数: {}", javaCount);
    }

    public static void m1(String[] args) throws IOException {
        final AtomicInteger dirCount = new AtomicInteger();
        final AtomicInteger fileCount = new AtomicInteger();
        Files.walkFileTree(Paths.get("G:\\note\\netty-demo\\src\\main\\java"), new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                log.info("遍历到的目录: {}", dir);
                dirCount.incrementAndGet();
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                log.info("遍历到的文件: {}", file);
                fileCount.incrementAndGet();
                return super.visitFile(file, attrs);
            }
        });

        log.info("文件夹的数量: {}, 文件的数量: {}", dirCount, fileCount);
    }
}
